<?php
namespace Xiaoc\Api;


/**
 * Xiaoc附近门店
 *
 * @author: zhy <zhy302813@163.com> 2017-8-19
 */

class Oto extends Common {
    
	public function getRules() {
            return array(
                'shoplist' => array(
                    'pos_x'   => array('name' => 'pos_x', 'require' => true,'desc'=>'纬度（X）' ),
                    'pos_y'   => array('name' => 'pos_y', 'require' => true,'desc'=>'经度（Y）' ),
                    'page'    => array('name' => 'page','require'=>true,'default'=>1,'min'=>1,'desc'=>'当前页数'),
                    'cat_id'   => array('name' => 'cat_id', 'default'=>0,'desc'=>'店铺类别ID' ),
                    'keywords'   => array('name' => 'keywords', 'desc'=>'店铺名称' )
                ),
                'shopinfo' => array(
                    'ru_id'   => array('name' => 'ru_id', 'require' => true,'min'=>1,'desc'=>'店铺ID' ),
                    'token'   => array('name' => 'token','desc'=>'用户Token' )
                ),
                'collect' => array(
                    'ru_id'   => array('name' => 'ru_id', 'require' => true,'min'=>1,'desc'=>'店铺ID' ),
                    'token'   => array('name' => 'token', 'require' => true,'desc'=>'用户Token' ),
                ),
                'article_info'  =>  array(
                    'article_id'    => array('name' => 'article_id', 'require' => true,'min'=>1,'desc'=>'文章ID' ),
                ),
                'article_list'  =>  array(
                    'keywords'    =>  array('name'=>'keywords','desc'=>'文章关键字'),
                    'cat_id'      =>  array('name'=>'cat_id','desc'=>'文章分类ID','type'=>'int'),
                    'page'        => array('name' => 'page','require'=>true,'default'=>1,'min'=>1,'desc'=>'分页'),
                ),
            );
        }
        
	/**
	 * 附近门店
	 * @desc 3km内门店列表
         * @return float latitude 纬度
         * @return float longitude 经度
         * @return string logo_thumb 图片地址
         * @return string rz_shopName 店铺名称
         * @return string shop_address 店铺地址
         * @return int cnum 关注数量
         * @return float length 距离此地（M）
         * @return float score 评分
         * @return int shoprz_type 店铺类型（1旗舰店2专卖店3/4专营店5批发店6门店）
	 */
	public function shoplist() {
           $limit = ($this->page - 1)*10;
           $where = '';
           if($this->keywords){
               $where = ' and ms.rz_shopName like "%'.$this->keywords.'%" ';
           }
           if ($this->cat_id){
               $cat_ids = $this->medoo->get('category','cat_id',array('parent_id'=>$this->cat_id));
               if (is_array($cat_ids)){
                   $where .= ' and ms.shop_categoryMain in ('.trim(implode(',',$cat_ids),',').')';
               }else{
                   $where .= 'and ms.shop_categoryMain = '.$cat_ids;
               }
           }
           if ($this->pos_x && $this->pos_y){
               $lat = round($this->pos_x,6);
               $lon = round($this->pos_y,6);
               $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
               $km = 'ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((ss.latitude * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((ss.latitude * 3.1415) / 180 ) *COS(('.$lon.'* 3.1415) / 180 - (ss.longitude * 3.1415) / 180 ) ) * 6380';
               $sql='select ms.shoprz_type,ss.ru_id,ss.latitude,ss.longitude,ss.logo_thumb,ms.rz_shopName,ss.shop_address,count(cs.rec_id) as cnum '.
                   'from '.$prefix.'seller_shopinfo as ss left join '.$prefix.'merchants_shop_information as ms on ss.ru_id = ms.user_id '.
                   'left join '.$prefix.'collect_store as cs on cs.ru_id = ss.ru_id '.
                   'where ss.latitude > '.$lat.'-1 and ss.latitude < '.$lat.'+1 and ss.longitude > '.$lon.'-1 and ss.longitude < '.$lon.'+1 '.$where.' group by cs.ru_id order by '.$km.' asc limit '.$limit.',10';
               $data['storelist'] = \PhalApi\DI()->notorm->seller_shopinfo->queryAll($sql, array());
               foreach($data['storelist'] as $key=>$vo){
                   $unit = 'm';
                   $length = round(distanceByLnglat($this->pos_x,$this->pos_y,$vo['latitude'],$vo['longitude']),1);
                   if($length > 1000){
                       $unit = 'km';
                       $length = round($length/1000,1);
                   }
                   $data['storelist'][$key]['length'] = $length.$unit;
                   $score = \PhalApi\DI()
                       ->notorm
                       ->comment_seller
                       ->select('desc_rank,service_rank,delivery_rank')
                       ->where(array('ru_id'=>$vo['ru_id']))
                       ->fetchAll();
                   $data['storelist'][$key]['score'] = 5.0 ;
                   if(count($score) > 0){
                       $scores = 0;
                       foreach ($score as $vo){
                           $scores += $vo['desc_rank'] + $vo['service_rank'] + $vo['delivery_rank'];
                       }
                       $fm = count($score) * 3;
                       $data['storelist'][$key]['score'] = round($scores/$fm,1);
                   }
                   if(isset($vo['logo_thumb']) && $vo['logo_thumb']){
                       $data['storelist'][$key]['logo_thumb'] = substr($vo['logo_thumb'], 3);
                   }
               }
               $data['has_more'] = true;

               $sql='select ss.latitude,ss.longitude,ss.logo_thumb,ms.rz_shopName,ss.shop_address '.
                   'from '.$prefix.'seller_shopinfo as ss left join '.$prefix.'merchants_shop_information as ms on ss.ru_id = ms.user_id '.
                   'where ss.latitude > '.$lat.'-1 and ss.latitude < '.$lat.'+1 and ss.longitude > '.$lon.'-1 and ss.longitude < '.$lon.'+1 '.$where.' order by '.$km.' asc limit '.$this->page * 10 .',1';
               $more = \PhalApi\DI()->notorm->seller_shopinfo->queryAll($sql, array());

               if(!count($more)){
                   $data['has_more'] = false;
               }
           }else{
               $data = array();
           }
            return $data;
	}
        /**
	 * 店铺详情
	 * @desc 附近店铺详情页
         * @return string notice 店铺介绍
         * @return string street_thumb 店铺头部图
         * @return string shop_address 店铺地址
         * @return string kf_tel 客服电话
         * @return string mobile 手机
         * @return string kf_welcomeMsg 营业时间
         * @return int score 店铺评分
         * @return float latitude 纬度
         * @return float longitude 经度
         * @return booleab is_collect 是否收藏
	 */
	public function shopinfo() {
            $storeinfo = \PhalApi\DI()
                        ->notorm
                        ->merchants_shop_information
                        ->select('rz_shopName')
                        ->where(array('user_id'=>$this->ru_id))
                        ->fetchOne();
               $data['shopinfo'] = \PhalApi\DI()
                        ->notorm
                        ->seller_shopinfo
                        ->select('ru_id,street_thumb,shop_address,kf_tel,mobile,notice,kf_welcomeMsg,latitude,longitude,shop_logo')
                        ->where(array('ru_id'=>$this->ru_id))
                        ->fetchOne();
               $data['shopinfo']['shop_name'] = $storeinfo['rz_shopName'];
               $score = \PhalApi\DI()
                        ->notorm
                        ->comment_seller
                        ->select('desc_rank,service_rank,delivery_rank')
                        ->where(array('ru_id'=>$this->ru_id))
                        ->fetchAll();
               $data['score'] = 5.0 ;
               if(count($score) > 0){
                   $scores = 0;
                   foreach ($score as $vo){
                       $scores += $vo['desc_rank'] + $vo['service_rank'] + $vo['delivery_rank']; 
                   }
                   $fm = count($score) * 3;
                   $data['score'] = round($scores/$fm,1);
               }
              $data['banner'] = \PhalApi\DI()
                        ->notorm
                        ->seller_shopslide
                        ->select('img_url')
                        ->where(array('ru_id'=>$this->ru_id,'is_show'=>1))
                        ->fetchAll();
              if(isset($data['banner']) && $data['banner']){
                  foreach($data['banner'] as $key=>$vo){
                      $data['banner'][$key]['img_url'] = substr($vo['img_url'],3);
                  }
              }
              $data['is_collect'] = false;
              if($this->token){
                  $userinfo = $this->check_login($this->token);
                  $rec_id = $this->medoo->get('collect_store','rec_id',array('user_id'=>$userinfo['user_id'],'ru_id'=>$this->ru_id));
                  if ($rec_id)$data['is_collect'] = true;
              }
              return $data;
	}
        /**
	 * 店铺收藏
	 * @desc 收藏店铺与取消
         * @return string msg 操作信息
         * @return boolean is_collect 是否收藏
	 */
        public function collect() {
            $userinfo = $this->get_users_info($this->token);
            $data['is_collect'] = false;
            if ($userinfo) {
                $collect = \PhalApi\DI()
                        ->notorm
                        ->collect_store
                        ->select('rec_id')
                        ->where(array('user_id' => $userinfo['user_id'], 'ru_id' => $this->ru_id))
                        ->fetchOne();
                if(isset($collect['rec_id']) && $collect['rec_id']){    //取消收藏
                    $cancel = \PhalApi\DI()->notorm->collect_store->where('rec_id', $collect['rec_id'])->delete();
                    if($cancel){
                        $data['msg'] = '已取消收藏！';
                        $data['is_collect'] = false;
                    }else{
                        $data['msg'] = '取消失败！';
                        $data['is_collect'] = true;
                    }
                }else{  //添加收藏
                    $data = array('user_id' => $userinfo['user_id'], 'ru_id' => $this->ru_id, 'add_time' => gmtime(),'is_attention'=>1);
                    \PhalApi\DI()->notorm->collect_store->insert($data);
                    $addid = \PhalApi\DI()->notorm->collect_store->insert_id();
                    if($addid){
                        $data['msg'] = '收藏成功！';
                        $data['is_collect'] = true;
                    }else{
                        $data['msg'] = '收藏失败！';
                        $data['is_collect'] = false;
                    }
                }
            }
            return $data;
        }

    /**
     * 文章分类
     * @desc 文章分类
     * @return string cat_name 分类名称
     * @return int cat_id 分类ID
     */
        public function article_cat_list(){
            $where['parent_id'] = 0;
            $where['show_in_nav'] = 1;
            $where['ORDER'] = array('sort_order'=>'DESC');
            $field = array('cat_name','cat_id');
            $list = $this->medoo->select('article_cat',$field,$where);
            return $list;
        }
        /**
         * 文章列表
         * @desc 文章列表
         * @return string title 文章标题
         * @return string add_time 发布时间
         * @return int article_id 文章ID
         */
        public function article_list(){
            $cat_id = $this->cat_id;
            $keywords = $this->keywords;
            $where = array();
            if ($cat_id>0){
                $cat_ids = $this->medoo->select('article_cat','cat_id',array('parent_id'=>$cat_id));
                if ($cat_ids){
                    $where['cat_id'] = $cat_ids;
                }
            }
            if ($keywords){
                $where['keywords[~]'] = trim($keywords);
            }
            $where['LIMIT']=array($this->limitStart,$this->limitEnd);
            $where['ORDER'] = array('add_time'=>'DESC');
            $list = $this->medoo->select('article',array('article_id','title','add_time'),$where);
            $count = 0;
            if ($list){
                foreach ($list as $key=>$value){
                    if ($value['add_time']){
                        $list[$key]['add_time'] = time_format($value['add_time']);
                    }
                }
                unset($where['LIMIT']);
                $count = $this->medoo->count('article','article_id',$where);
            }else{
                $list = array();
            }
            $data['list'] = $list;
            $data['hasmore'] = $this->HasMore($count);
            return $data;
        }
        /**
         * 文章详情
         * @desc 文章详情
         * @return string title 文章标题
         * @return string add_time 发布时间
         * @return string content 文章内容
         */
        public function article_info(){
            $article_id = $this->article_id;
            if (intval($article_id)>0){
                $info = $this->medoo->get('article',array('title','add_time','content'),array('article_id'=>$article_id));
                $info['add_time'] = time_format($info['add_time']);
                if (empty($info)) $info = array();
            }
            return $info;
        }
}
